package com.congee02.modelshellmvn.manager.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.congee02.modelshellmvn.entity.account.Account;
import com.congee02.modelshellmvn.exception.AccountInvalidToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@Slf4j
public class AccountJwtValidator {

    @Resource
    private Algorithm algorithm;

    public Account tryExtractInfo(Account account) {
        try {
            JWTVerifier verifier = JWT.require(
                    algorithm
            ).build();

            String jwt = account.getJwt();
            if (jwt == null) {
                throw new AccountInvalidToken();
            }

            DecodedJWT decoded = verifier.verify(
                    jwt
            );

            return account
                    .setUsername(
                            decoded.getSubject()
                    )
                    .setRole(
                            decoded.getClaim(
                                    JwtClaims.ROLE
                            ).asInt()
                    );
        } catch (JWTVerificationException e) {
            log.warn("Invalid Token", e);
            throw new AccountInvalidToken();
        }
    }

}
